﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.Abstractions;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.ValueProviders.Interfaces;

namespace RoketSolutions.SP2010.Infrostructure.UI.Ajax.ValueProviders
{
    public class ValueProviderFactoryCollection : Collection<ValueProviderFactory>
    {
         public ValueProviderFactoryCollection()
         {
         }

        public ValueProviderFactoryCollection(IList<ValueProviderFactory> factories) : base(factories)
        {
        }

        public IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            var result = new ValueProviderCollection((
                                    from factory in this
                                    let provider = factory.CreateProvider(controllerContext)
                                    where provider != null
                                    select provider).ToList());
            return result;
        }
    }


    public class ValueProviderCollection : Collection<IValueProvider>, IValueProvider
    {
        public ValueProviderCollection()
        {
        }

        public ValueProviderCollection(IList<IValueProvider> valueProviders) : base(valueProviders)
        {
        }

        public bool ContainsPrefix(string modelName)
        {
            return ContainsPrefix(modelName, true);
        }

        public bool ContainsPrefix(string modelName, bool matchExact)
        {
            return this.Any(provider => provider.ContainsPrefix(modelName, matchExact));
        }

        public bool ContainsMatchPrefix(string keyPattern)
        {
            return this.Any(provider => provider.ContainsMatchPrefix(keyPattern));
        }

        public List<string> GetMatchPrefix(string keyPattern)
        {
            return (from provider in this
                    let value = provider.GetMatchPrefix(keyPattern)
                    where value != null
                    select value).FirstOrDefault();
        }


        public ValueProviderResult GetValue(string key)
        {
            return (from provider in this
                    let value = provider.GetValue(key)
                    where value != null
                    select value).FirstOrDefault();
        }

    }
}